package com.gisluq.runtimeviewer3d.BMOD.RootAct;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Handler;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.gisluq.runtimeviewer3d.BMOD.ProjectsModule.View.MainActivity;
import com.gisluq.runtimeviewer3d.Config.AppWorksSpaceInit;
import com.gisluq.runtimeviewer3d.Permission.PermissionsActivity;
import com.gisluq.runtimeviewer3d.Permission.PermissionsChecker;
import com.gisluq.runtimeviewer3d.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import gisluq.lib.Util.AppUtils;
import gisluq.lib.Util.SysUtils;
import gisluq.lib.Util.ToastUtils;

/**
 * 应用程序初始化页面
 */
public class InitActivity extends AppCompatActivity {

    private static String TAG = "InitActivity";
    private final int SPLASH_DISPLAY_LENGHT = 2000; // 延迟时间
    private Context context = null;

    private static final int REQUEST_CODE = 0; // 请求码
    // 所需的全部权限
    private static final String[] PERMISSIONS = new String[]{
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,//写入存储
            Manifest.permission.ACCESS_FINE_LOCATION,//位置信息
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA //相机
    };
    private static PermissionsChecker mPermissionsChecker; // 权限检测器

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        setContentView(R.layout.activity_init);

        /**
         * RuntimeViewer3D  assert中的文件夹
         * tempPath  要复制到的文件夹的名称(全路径)
         */
        String tempPath=context.getFilesDir().getAbsolutePath()+"/"+"RuntimeViewer3D";
        copyAssertDirToData(this,"RuntimeViewer3D",tempPath);
        mPermissionsChecker = new PermissionsChecker(this);
        // 缺少权限时, 进入权限配置页面
        if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
            startPermissionsActivity();
        } else {
            goMain();
        }


    }

    /**
     * 跳转
     */
    private void startActivity() {
        Intent mainIntent = new Intent(context, MainActivity.class);
        context.startActivity(mainIntent);
        ((Activity) context).finish();
    }

    /**
     * 应用程序初始化
     */
    private void appInit() {
        boolean isOk = AppWorksSpaceInit.init(context);//初始化系统文件夹路径
        TextView textView = (TextView) this.findViewById(R.id.activity_init_versionTxt);
        String version = AppUtils.getVersionName(this);
        textView.setText("版本号:" + version);
        new Handler(Looper.myLooper()).postDelayed(new Runnable() {
            public void run() {
                try {
                    startActivity();
                } catch (Exception e) {
                    Log.e(TAG, e.toString());
                }
            }
        }, SPLASH_DISPLAY_LENGHT);
    }

    /**
     * 弹出权限获取提示信息
     */
    private void startPermissionsActivity() {
        PermissionsActivity.startActivityForResult(this, REQUEST_CODE, PERMISSIONS);
    }


    /**
     * 将asset里面的文件复制到
     * /data/user/0/报名/files 中
     *
     * @param context
     * @param assertName
     */
    private void loadAssetsToCache(Context context, String assertName) {
        String filePath = this.getFilesDir().getAbsolutePath();
        AssetManager assetManager = context.getAssets();
        try {
            InputStream inputStream = assetManager.open(assertName);
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            //保存到本地的文件夹下的文件
            FileOutputStream fileOutputStream = new FileOutputStream(filePath + "/" + assertName);
            byte[] buffer = new byte[1024];
            int count = 0;
            while ((count = inputStream.read(buffer)) > 0) {
                fileOutputStream.write(buffer, 0, count);
            }
            fileOutputStream.flush();
            fileOutputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void copyAssertDirToData(Context context, String assetDir, String dir) {
        String[] files;
        try {
            files = context.getResources().getAssets().list(assetDir);
        } catch (IOException e1) {
            return;
        }
        File mWorkingPath = new File(dir);
        if (!mWorkingPath.exists()) {
            mWorkingPath.mkdirs();
        }
        for (int i = 0; i < files.length; i++) {
            try {
                String fileName = files[i];
                if (!fileName.contains(".")) {
                    if (0 == assetDir.length()) {
                        copyAssertDirToData(context, fileName, dir + fileName + "/");
                    } else {
                        copyAssertDirToData(context, assetDir + "/" + fileName, dir +"/"+fileName);
                    }
                    continue;
                }
                File outFile = new File(mWorkingPath, fileName);
                if (outFile.exists()) {
                    outFile.delete();
                }
                InputStream in = null;
                if (0 != assetDir.length()){
                    in = context.getAssets().open(assetDir + "/" + fileName);
                }else{
                    in = context.getAssets().open(fileName);
                }
                OutputStream out = new FileOutputStream(outFile);
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                in.close();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            if (resultCode == PermissionsActivity.PERMISSIONS_DENIED) {
                //权限被拒绝
            } else if (resultCode == PermissionsActivity.PERMISSIONS_GRANTED) {
                //权限被授予
            }
            goMain();
        }
    }

    private void goMain(){
        boolean isOk = AppWorksSpaceInit.init(context);//初始化系统文件夹路径
        TextView textView = (TextView) this.findViewById(R.id.activity_init_versionTxt);
        String version = AppUtils.getVersionName(this);
        textView.setText("版本号:" + version);
        new Handler(Looper.myLooper()).postDelayed(new Runnable() {
            public void run() {
                try {
                    startActivity();
                } catch (Exception e) {
                    Log.e(TAG, e.toString());
                }
            }
        }, SPLASH_DISPLAY_LENGHT);
    }
}
